#/bin/python
#coding:utf8
'''
Created on 2011-4-30

@author: mark
'''
from __future__ import with_statement

import web
import config
import os
from model import problem
from model import ptype
from model import comment
from model import user
from model import choice
from model import answer
from util import auth
from util import page
from util import basic

tp = config.template_problem
tp_user = config.template_user
db = config.database

class createProblem:
    @auth.login
    def POST(self):
        try:
            with db.transaction():
                i = web.input(picture1={}, picture2={}, autoclose=None, pcomment=None)    
                current_user = web.ctx.session['current_user']
            
                title = i['title']
                pdesc = i['description']
                type = i['type']
                
                pid = problem.createproblem(title, pdesc, current_user['uid'], type, 0, 1)
                
                if i['autoclose']:
                    year = i["year"]
                    month = i['month']
                    day = i['day']
                    
                    expectdate = "%s-%s-%s" % (year, month, day)
                    problem.addAutoCloseProblem(pid, expectdate)
                    problem.updateProblemAutoComplete(pid, expectdate)
                    
                if i['pcomment']:
                    problem.updateProblemPubComment(pid, 1)
                    
                if 'picture1' in i:
                    filepath1 = os.path.join(config.problem_path, basic.problemPhotoname(i['picture1'].filename, pid, 1))
                    photo1 = config.problem_image_path + basic.problemPhotoname(i['picture1'].filename, pid, 1)
                    try:
                        fout = open(filepath1, 'wb')
                        fout.write(i.picture1.file.read())
                        fout.close()
                    except Exception, e:
                        return e
                    
                if 'picture2' in i:
                    filepath2 = os.path.join(config.problem_path, basic.problemPhotoname(i['picture2'].filename, pid, 2))
                    photo2 = config.problem_image_path + basic.problemPhotoname(i['picture2'].filename, pid, 2)
                    try:
                        fout = open(filepath2, 'wb')
                        fout.write(i.picture2.file.read())
                        fout.close()
                    except Exception, e:
                        return e
                
                choice1 = i['choice1']
                choice2 = i['choice2']   
                 
                try:
                    choice.createchoice(pid, choice1, photo1, 1)
                    choice.createchoice(pid, choice2, photo2, 2)
                except Exception, e:
                    return e
                
                return web.seeother("/userhome/%s/" % current_user['uid'])
        except Exception,e:
            return e

        
    @auth.login
    def GET(self):
        types = ptype.getTypes()
        current_user = web.ctx.session['current_user']
        context = {"types":types, \
                   "user":current_user, \
                   }
        return tp.createproblem(context)
    
class problemsByType:
    def GET(self, tid=None):
        i = web.input(start=None)
        start = i['start']
        
        try:
            s = 0 if start is None else int(start)
        except Exception:
            s = 0
        
        if tid:
            problems = problem.getProblemsByType(tid, s)
            max_resuts = ptype.getTypeProblemCount(tid)
        # for url /type/
        else:
            problems = problem.getAllProblems(s)
            max_resuts = ptype.getAllProblemCount()
        
        pages = page.get_paging(s, max_resuts)
        type = ptype.getType(tid) if tid else None
        
        urlbase = "/type/%s?start=" % tid if tid else "/type?start="
        
        monthHotProblems = problem._getMonthHotProblems(10)
        weekHotProblems = problem._getWeekHotProblems(10)
        
        context = {"problems":problems, \
                 "pages":pages, \
                 "type":type, \
                 "urlbase":urlbase, \
                 "monthHotProblems":monthHotProblems, \
                 "weekHotProblems":weekHotProblems
                 }
        return tp.typeProblem(context)
    
    
class probleminfo:
    def GET(self, pid):
        pid = int(pid)
        pro = problem.getproblembyid(pid)
        choose_a, choose_b = choice.getchoicebypid(pid)
        coments = comment.getCommentsByPid(pid)
        type = ptype.getType(pro.type)
        types = ptype.getTypes()
        
        user = web.ctx.session['current_user']
        
        monthHotProblems = problem._getMonthHotProblems(10)
        weekHotProblems = problem._getWeekHotProblems(10)
        
        content = {"problem":pro, \
                 "choose_a":choose_a, \
                 "choose_b":choose_b, \
                 "comments":coments, \
                 "type":type, \
                 "types":types, \
                 "user":user, \
                 "monthHotProblems":monthHotProblems, \
                 "weekHotProblems":weekHotProblems
                 }
        
        return tp.problemVote(content)
        

class modifyProblem:
    @auth.login
    def GET(self, pid):        
        prob = problem.getproblembyid(pid)
        current_user = web.ctx.session['current_user']
        
        protype = ptype.getType(prob.type)
        pchoice = choice.getchoicebypid(prob.pid)
        pcho = choice.getchoicebypid(prob.pid)
        alltypes = ptype.getTypes()
        
        context = {"problem":prob, \
                   "type":protype, \
                   "choice":pchoice, \
                   "choices":pcho, \
                   "user":current_user, \
                   "alltypes":alltypes, \
                   }
        
        return tp.modifyproblem(context)
    
    
    @auth.login
    def POST(self, pid):
        try:
            with db.transaction():       
                i = web.input(picture1={}, picture2={}, autocomplete=None)    
                current_user = web.ctx.session['current_user']
            
                title = i['title']
                pdesc = i['description']
                type = i['type']
                
                problem.modifyproblem(pid, title, pdesc, type)
                
                if i['autocomplete']:
                    year = i["year"]
                    month = i['month']
                    day = i['day']
                    
                    expectdate = "%s-%s-%s" % (year, month, day)
                    problem.modifyAutoCloseProblem(pid, expectdate)
                    problem.updateProblemAutoComplete(pid, expectdate)
                
                if 'picture1' in i:
                    uploadPhoto('picture1',1)
                    
                if 'picture2' in i:
                    uploadPhoto('picture2',2)
                
                choice1 = i['choice1']
                choice2 = i['choice2']   
                 
                try:
                    photo1 = config.problem_image_path + basic.problemPhotoname(i['picture1'].filename, pid, 1)
                    choice.modifychoice(pid, choice1,photo1,  1)
                    photo2 = config.problem_image_path + basic.problemPhotoname(i['picture2'].filename, pid, 2)
                    choice.modifychoice(pid, choice2, photo2, 2)
                except Exception, e:
                    print e
                
                return web.seeother("/userhome/%s/" % current_user['uid'])
        except Exception,e:
            return e
        
      
        def uploadPhoto(pictureItem,pictureID):
            filepath1 = os.path.join(config.problem_path, basic.problemPhotoname(i[pictureItem].filename, pid, pictureID))
            try:
                fout = open(filepath1, 'wb')
                fout.write(i.picture1.file.read())
                fout.close()
            except Exception, e:
                return e      
    
class addComment:
    def POST(self, pid):
        i = web.input()
        content = i['content']
        res = comment.addComment(pid, content)
        return web.seeother("/problem/%s/" % pid)
